from PyQt6.QtCore import *
from PyQt6 import QtCore
from PyQt6 import QtWidgets

import typing

import asyncio
from client_core import QAsyncSsdevRpcResolver, SsdevRpcNode


class SsdevRpcModel(QAbstractItemModel):
    def __init__(self, root: SsdevRpcNode, parent=None):
        super(SsdevRpcModel, self).__init__(parent)
        self.root = root

    def rowCount(self, parent: QModelIndex = ...) -> int:
        if parent.isValid():
            return parent.internalPointer().child_count()
        return self.root.child_count()

    def columnCount(self, parent: QModelIndex = ...) -> int:
        if parent.isValid():
            return parent.internalPointer().column_count()
        return self.root.column_count()

    def index(self, row: int, column: int, parent: QModelIndex = ...) -> QModelIndex:
        if not parent or not parent.isValid():
            p = self.root
        else:
            p = parent.internalPointer()

        if not QAbstractItemModel.hasIndex(self, row, column, parent):
            return QModelIndex()

        child = p.child(row)
        if child:
            return QAbstractItemModel.createIndex(self, row, column, child)
        else:
            return QModelIndex()

    def parent(self, child: QModelIndex) -> QModelIndex:
        if child.isValid():
            p = child.internalPointer().parent()
            if p:
                return QAbstractItemModel.createIndex(self, p.row(), 0, p)
        return QModelIndex()

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if not index.isValid():
            return None
        node = index.internalPointer()
        if role == QtCore.Qt.ItemDataRole.DisplayRole:
            return node.data(index.column())
        return None